// 图像和视频逻辑
const photoList = document.querySelector('#photo-list');
const photoView = document.querySelector('#photo-view');
const videoList = document.querySelector('#video-list');
const videoView = document.querySelector('#video-view');

photoList.addEventListener('click', (e) => {
  for (let node of photoList.children) {
    node.classList.remove('active');
  }
  e.target.classList.add('active');
  photoView.src = e.target.dataset.src;
});

videoList.addEventListener('click', (e) => {
  for (let node of videoList.children) {
    node.classList.remove('active');
  }
  e.target.classList.add('active');
  videoView.src = e.target.dataset.src;
});

function receiveMediaList(parent) {
  return async (res) => {
    const data = await res.json();
    data['dataList'].forEach((item) => {
      const li = document.createElement('li');
      li.textContent = item.name;
      li.setAttribute('data-src', item.src);
      parent.appendChild(li);
    });
    parent.firstElementChild.click();
  };
}

fetch('/photo-list').then(receiveMediaList(photoList, photoView));
fetch('/video-list').then(receiveMediaList(videoList, videoView));

// 数据集初始化
const selectLeft = document.querySelector('#select-left');
const selectRight = document.querySelector('#select-right');

function changeInputData(name) {
  selectLeft.disabled = true;
  selectRight.disabled = true;
  btnLeft.disabled = true;
  btnRight.disabled = true;
  fetch('/input-data', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ name }),
  }).finally(() => {
    selectLeft.disabled = false;
    selectRight.disabled = false;
    btnLeft.disabled = false;
    btnRight.disabled = false;
  });
}

selectLeft.addEventListener('change', (e) => changeInputData(e.target.value));
selectRight.addEventListener('change', (e) => changeInputData(e.target.value));

function receiveInputData() {
  return async (res) => {
    const data = await res.json();
    data['dataList'].forEach((item) => {
      selectLeft.add(new Option(item, item));
      selectRight.add(new Option(item, item));
    });
    changeInputData(data['dataList'][0]);
  };
}

fetch('/input-data').then(receiveInputData());

// 初始化图表
const standardInitOption = {
  title: {
    text: '标准输出',
  },
  grid: {
    top: 32,
    right: 32,
    bottom: 32,
    left: 32,
  },
  tooltip: {
    trigger: 'axis',
  },
  xAxis: {
    type: 'category',
    data: [],
  },
  yAxis: {
    type: 'category',
    data: [0, 1],
  },
  series: [
    {
      itemStyle: {
        color: '#fff',
      },
      name: 'result',
      type: 'line',
      step: 'start',
      data: [],
    },
  ],
};

const outputInitOption = {
  title: {
    text: '测试输出',
  },
  grid: {
    top: 32,
    right: 32,
    bottom: 32,
    left: 32,
  },
  tooltip: {
    trigger: 'axis',
  },
  xAxis: {
    type: 'category',
    data: [],
  },
  yAxis: {
    type: 'category',
    data: [0, 1],
  },
  series: [
    {
      itemStyle: {
        color: '#1ff6ff',
      },
      name: 'result',
      type: 'line',
      step: 'start',
      data: [],
    },
  ],
};

const standardLeft = echarts.init(document.querySelector('#standard-left'), 'dark');
const outputLeft = echarts.init(document.querySelector('#output-left'), 'dark');
const standardRight = echarts.init(document.querySelector('#standard-right'), 'dark');
const outputRight = echarts.init(document.querySelector('#output-right'), 'dark');

standardLeft.setOption(standardInitOption);
outputLeft.setOption(outputInitOption);
standardRight.setOption(standardInitOption);
outputRight.setOption(outputInitOption);

// 测试按钮功能
const btnLeft = document.querySelector('#button-left');
const btnRight = document.querySelector('#button-right');
const accuracyLeft = document.querySelector('#accuracy-left');
const accuracyRight = document.querySelector('#accuracy-right');

btnLeft.addEventListener('click', () => {
  standardLeft.setOption(standardInitOption);
  outputLeft.setOption(outputInitOption);
  btnLeft.disabled = true;
  accuracyLeft.textContent = '';
  let leftIt = 0;
  let count = 0;
  fetch('/output')
    .then((res) => res.json())
    // .then((data) => {
    //   accuracyLeft.textContent = `准确率：${(data.accuracy * 100).toFixed(2)}%`;
    //   return data;
    // })
    .then((data) => {
      return new Promise((resolve) => {
        const cb = () => {
          if (count === data.standard.length) {
            cancelAnimationFrame(leftIt);
            return resolve(data.accuracy);
          }
          const standardOption = standardLeft.getOption();
          standardOption.series[0].data.push(data.standard[count]);
          standardOption.xAxis[0].data.push(count);
          standardLeft.setOption(standardOption);

          const outputOption = outputLeft.getOption();
          outputOption.series[0].data.push(data.output[count]);
          outputOption.xAxis[0].data.push(count);
          outputLeft.setOption(outputOption);

          count++;
          requestAnimationFrame(cb);
        };
        cancelAnimationFrame(leftIt);
        requestAnimationFrame(cb);
      });
    })
    .then((acc) => {
      accuracyLeft.textContent = `准确率：${(acc * 100).toFixed(2)}%`;
    })
    .finally(() => {
      btnLeft.disabled = false;
    });
});

btnRight.addEventListener('click', () => {
  standardRight.setOption(standardInitOption);
  outputRight.setOption(outputInitOption);
  btnRight.disabled = true;
  accuracyRight.textContent = '';
  let rightIt = 0;
  let count = 0;
  fetch('/output')
    .then((res) => res.json())
    // .then((data) => {
    //   accuracyRight.textContent = `准确率：${(data.accuracy * 100).toFixed(2)}%`;
    //   return data;
    // })
    .then((data) => {
      return new Promise((resolve) => {
        const cb = () => {
          if (count === data.standard.length) {
            cancelAnimationFrame(rightIt);
            return resolve(data.accuracy);
          }
          const standardOption = standardRight.getOption();
          standardOption.series[0].data.push(data.standard[count]);
          standardOption.xAxis[0].data.push(count);
          standardRight.setOption(standardOption);

          const outputOption = outputRight.getOption();
          outputOption.series[0].data.push(data.output[count]);
          outputOption.xAxis[0].data.push(count);
          outputRight.setOption(outputOption);

          count++;
          requestAnimationFrame(cb);
        };
        cancelAnimationFrame(rightIt);
        requestAnimationFrame(cb);
      });
    })
    .then((acc) => {
      accuracyRight.textContent = `准确率：${(acc * 100).toFixed(2)}%`;
    })
    .finally(() => {
      btnRight.disabled = false;
    });
});
